package org.nowcoder.leetcode.BTree;

import java.util.ArrayDeque;

/**
 * Title  : 230. Kth Smallest Element in a BST
 * Source : https://leetcode.cn/problems/kth-smallest-element-in-a-bst/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-09-14
 */

public class LeetCode_230 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int kthSmallest(TreeNode root, int k) {
        int result = 0;
        ArrayDeque<TreeNode> sta = new ArrayDeque<>();
        TreeNode p = root;
        int i = 0;
        while (p != null || !sta.isEmpty()) {
            while (p != null) {
                sta.push(p);
                p = p.left;
            }
            TreeNode node = sta.pop();
            if (i == k - 1) {
                result = node.val;
                break;
            }
            i++;
            p = node.right;
        }
        return result;
    }
}
